package logic

import (
	"context"
	"encoding/json"
	"fmt"

	"lottery-zero/internal/model"
	"lottery-zero/internal/svc"
	"lottery-zero/internal/types"

	"github.com/tal-tech/go-zero/core/logx"
	"gorm.io/gorm"
)

type LottogetbetLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLottogetbetLogic(ctx context.Context, svcCtx *svc.ServiceContext) LottogetbetLogic {
	return LottogetbetLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LottogetbetLogic) Lottogetbet(req types.LottoTicksPageReq, userId string) (*types.LottoTicksPageReply, error) {
	userInt, _ := json.Number(userId).Int64()
	var tx *gorm.DB
	switch req.Mode {
	case 0:
		// 未开奖投注,包括长期投注
		tx = l.svcCtx.PGDB.Model(&model.UserLotteryTicket{}).Where("user_id = ? AND is_open = ?", userInt, false)
	case 1:
		// 中奖的彩票
		tx = l.svcCtx.PGDB.Debug().Model(&model.UserLotteryTicket{}).Where("user_id = ? AND is_open = ?", userInt, true).Not("a=0 AND b=0 AND c=0 AND d=0 AND e=0 AND f=0 AND g=0 AND h=0 AND i=0")
	case 2:
		// 没有中奖的彩票
		tx = l.svcCtx.PGDB.Model(&model.UserLotteryTicket{}).Where("user_id = ? AND is_open = ? AND a=0 AND b=0 AND c=0 AND d=0 AND e=0 AND f=0 AND g=0 AND h=0 AND i=0", userInt, true)
	}
	var (
		total     int64
		pageCount int64
		page      int64
	)
	tx.Count(&total)

	// 计算 page count
	pageCount = total / req.PageSize
	if total%req.PageSize > 0 {
		pageCount++
	}

	// 计算page
	if req.Page == 0 {
		page = 1
	} else if req.Page > pageCount {
		page = pageCount
	} else {
		page = req.Page
	}

	// 获取分页后的内容
	ubs := []model.UserLotteryTicket{}
	tx.Limit(int(req.PageSize)).Offset(int((page - 1) * req.PageSize)).Find(&ubs)

	// 计算其中奖情况
	for index := range ubs {
		ubs[index].GetAward()
	}

	fmt.Println(req.Mode, req.Page, req.PageSize)
	return &types.LottoTicksPageReply{
		Page:      page,
		PageSize:  req.PageSize,
		Total:     total,
		PageCount: pageCount,
		Data:      ubs,
	}, nil
}
